<?php
require_once __DIR__ . '/vendor/autoload.php';

use Workerman\Worker;
use Workerman\WebServer;
use Workerman\Autoloader;

// 创建 WebSocket 服务器，监听 2346 端口
// $ws_worker = new Worker("websocket://0.0.0.0:2346");

$worker = new Worker('websocket://0.0.0.0:2346', [
    // 'ssl' => [
    //     'local_cert'  => '/moqixiaozhen.icu_apache_ecc/moqixiaozhen.icu_public.crt', // 证书路径
    //     'local_pk'    => '/moqixiaozhen.icu_apache_ecc/moqixiaozhen.icu.key',     // 私钥路径
    //     'verify_peer' => false,
    //     'allow_self_signed' => true, // 如果是自签名证书需要此项
    // ],
    'ssl' => [
        'local_cert'  => '/test/server.crt', // 证书路径
        'local_pk'    => '/test/server.key',     // 私钥路径
        'verify_peer' => false,
        'allow_self_signed' => true, // 如果是自签名证书需要此项
    ],
    // 'rejectUnauthorized' => false
]);

// 启动 4 个进程对外提供服务
$ws_worker->count = 4;

$G=[];

// 连接建立时的回调
$ws_worker->onConnect = function($connection) {
    $client_ip = $connection->getRemoteIp();
    $client_port = $connection->getRemotePort();
    $connection_id = $connection->id;
    
    echo "✅ 新的WebSocket连接: {$client_ip}:{$client_port} [ID: {$connection_id}]\n";
    
    // 记录连接日志
    $log_data = [
        'action' => 'connect',
        'client_ip' => $client_ip,
        'client_port' => $client_port,
        'connection_id' => $connection_id,
        'timestamp' => date('Y-m-d H:i:s')
    ];
    echo "📝 连接日志: " . json_encode($log_data) . "\n";
    
    // 发送欢迎消息
    $welcome_msg = [
        'action' => 'welcome',
        'data' => '连接成功',
        // 'connection_id' => $connection_id,
        'timestamp' => time()
    ];
    $connection->send(json_encode($welcome_msg));
};

// 收到消息时的回调
$ws_worker->onMessage = function($connection, $data) {
    $client_ip = $connection->getRemoteIp();
    $connection_id = $connection->id;
    
    echo "📨 收到来自 {$client_ip} 的消息: {$data}\n";
    
    try {
        // 尝试解析 JSON 消息
        $message_data = json_decode($data, true);
        
        handleTextMessage($connection, $message_data);
    } catch (Exception $e) {
        $error_response = [
            'type' => 'error',
            'message' => '消息处理失败',
            'error' => $e->getMessage()
        ];
        $connection->send(json_encode($error_response));
    }
};

// 连接关闭时的回调
$ws_worker->onClose = function($connection) {
    $client_ip = $connection->getRemoteIp();
    $connection_id = $connection->id;
    
    echo "❌ 连接关闭: {$client_ip} [ID: {$connection_id}]\n";
    
    $log_data = [
        'action' => 'disconnect',
        'client_ip' => $client_ip,
        'connection_id' => $connection_id,
        'timestamp' => date('Y-m-d H:i:s')
    ];
    echo "📝 断开日志: " . json_encode($log_data) . "\n";
};

// 错误处理
$ws_worker->onError = function($connection, $code, $msg) {
    echo "🚨 WebSocket错误 [{$code}]: {$msg}\n";
};



/**
 * 处理文本消息
 */
function handleTextMessage($connection, $text) 
{
    $res="{}";
    try {
        $ac = $text["action"];

        switch ($ac) {
            // case 'login':
            //     $res = handleLogin($connection, $request);
            // case 'heartbeat':
            //     $res = handleHeartbeat($connection, $request);
                

            case 'chat':
                $res = handleChat($connection, $text);
                break;
            case 'getchat':
                // return "";
                $res = handleGetChat($connection, $text);
                break;
            default:
                $res = [
                    'action' => 'error',
                    'code' => 404,
                    'message' => "UnKnow: {$ac}",
                    'timestamp' => time()
                ];
                break;
        }
    } catch (Exception $e) {
        $res = [
            'action' => 'error',
            'code' => 500,
            'data' => '业务处理错误: ' . $e->getMessage(),
            'timestamp' => time()
        ];
    }
    

    $connection->send(json_encode($res));
}

function handleGetChat($connection, $request)
{
    global $G;
    // // 检查认证
    $date = json_decode($request['data'],true);
    $day = date("Y-m-d");

    $res=[];
    $res["data"]=[];
    $res["count"]=[];

    echo json_encode($G, JSON_UNESCAPED_UNICODE);
    echo "\n";
    echo json_encode($date, JSON_UNESCAPED_UNICODE);

    if(empty($G["chat"])){
        $G["chat"]=[];
        
        $G["chat"][$date]=[];
    }else{
        // 假设 $G["chat"] 的 key 是日期格式，如 '2024-01-15'
        foreach ($G["chat"] as $dateKey => $value) {
            // 将数组key和比较日期转换为时间戳
            $keyTimestamp = strtotime($dateKey);
            $compareTimestamp = strtotime($day);

            echo $dateKey."\n";
            echo isset($date[$dateKey])."\n";
            echo json_encode($date, JSON_UNESCAPED_UNICODE);
    
            // 判断key是否比$date2早2天或以上
            if ($compareTimestamp - $keyTimestamp >= 2 * 24 * 60 * 60) {
                 // 删除这个key
                unset($G["chat"][$dateKey]);
                echo "删除过期key: {$dateKey}\n";
            }else if(isset($date[$dateKey])){
                $index1 = $date[$dateKey];
                $index2 = count($G["chat"][$dateKey])-1;
                $len = $index2-$index1+1;

                echo $index1."  ".$index2."  ".$len."\n";
                if($index1-$index2>0){
                    echo "-0000000000000000-\n";
                }else if($index1-$index2==0){
                    echo "----------------------\n";
                    $list = [];
                    $list[] = $G["chat"][$dateKey][$index2];
                    $res["data"][$dateKey] = $list;
                    $res["count"][$dateKey] = $index2+1;
                }else{
                    echo "=====================\n";
                    $res["data"][$dateKey] = array_slice($G["chat"][$dateKey],$index1,$len);
                    $res["count"][$dateKey] = $index2+1;
                }
            }
        }
        if(!isset($G["chat"][$date])){
            $G["chat"][$date]=[];
        }
    }
   
    echo json_encode($res, JSON_UNESCAPED_UNICODE);

    return [
        'action' => 'getchat_response',
        'code' => 200,
        'data' => json_encode($res),
        'timestamp' => time()
    ];
}

/**
 * 处理获取数据请求的函数
 */
function handleChat($connection, $request)
{
    global $G;
    echo "================聊天处理";
    // // 检查认证
    
    $dd = json_decode($request['data'],true);
    echo json_encode($dd, JSON_UNESCAPED_UNICODE) . "\n";
    $date = date("Y-m-d");
    $c=[];

    if(empty($G["chat"])){
        $G["chat"]=[];
        
        $G["chat"][$date]=[];
    }else{
        // 假设 $G["chat"] 的 key 是日期格式，如 '2024-01-15'
        foreach ($G["chat"] as $dateKey => $value) {
            // 将数组key和比较日期转换为时间戳
            $keyTimestamp = strtotime($dateKey);
            $compareTimestamp = strtotime($date);
    
            // 判断key是否比$date2早2天或以上
            if ($compareTimestamp - $keyTimestamp >= 2 * 24 * 60 * 60) {
                 // 删除这个key
                unset($G["chat"][$dateKey]);
                echo "删除过期key: {$dateKey}\n";
            }else{
                $c[$dateKey] = count($G["chat"][$dateKey]);
            }
        }
        if(empty($G["chat"][$date])){
            $G["chat"][$date]=[];
        }
    }
    $dd["index"]=count($G["chat"][$date]);

    $G["chat"][$date][] = $dd;

    echo "聊天记录\n";
    echo json_encode($G["chat"], JSON_UNESCAPED_UNICODE);

    return [
        'action' => 'chat_response',
        'code' => 200,
        'data' => json_encode($c),
        'timestamp' => time()
    ];
}



/**
 * 广播消息给所有连接
 */
function broadcast($message, $sender_connection = null) {
    $message_json = is_string($message) ? $message : json_encode($message);
    
    global $ws_worker;
    foreach ($ws_worker->connections as $connection) {
        // 如果不发送给发送者，跳过
        if ($sender_connection && $connection === $sender_connection) {
            continue;
        }
        $connection->send($message_json);
    }
}

/**
 * 广播给除发送者外的所有连接
 */
function broadcastToOthers($message, $sender_connection) {
    broadcast($message, $sender_connection);
}

// 运行 worker
Worker::runAll();